/*
 * @Author: ayun chengyunwu@jiatui.com
 * @Date: 2023-05-10 15:56:43
 * @LastEditors: ayun chengyunwu@jiatui.com
 * @LastEditTime: 2023-05-15 10:48:37
 * @FilePath: /ift-economy-h5/src/pages/Investment-intention/components/FormTable/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { BaseSyntheticEvent, useEffect, useState } from "react";
import Styles from "./index.module.scss";

// 根据栏目生成表格数据
export const getTableData = (data: any, len: number) =>
  data.reduce(
    (prev: string, cur: string) => [
      ...prev,
      [cur, ...Array.from({ length: len }, () => "")],
    ],
    []
  );

type PropT = {
  value?: [];
  theadData?: string[];
  titleColumnData?: string[];
  onChange?: (data: []) => void;
  readOnly?: boolean;
  extraData?: [];
  extraTd?:
    | ((item: number, firstIndex: number, index: number) => string | any)
    | string;
};

const Index = ({
  theadData = [],
  readOnly = false,
  titleColumnData = [],
  extraData = [],
  onChange,
  value,
  extraTd,
}: PropT) => {
  const [inputData, setInputData] = useState(
    getTableData(titleColumnData, theadData.length)
  );

  useEffect(() => {
    if (value?.length) {
      setInputData(value);
    }
    return () => {};
  }, [value]);

  // 处理输入框事件
  const handleChange = (e: BaseSyntheticEvent) => {
    const {
      value,
      dataset: { firstIndex, lastIndex },
    } = e.target;

    const res = inputData;
    res[firstIndex][lastIndex] = value;
    setInputData([...res]);

    onChange && onChange(res);
  };

  return (
    <table border={1} className={`${Styles.container}`}>
      <thead className={`${Styles.thead}`}>
        <tr>
          <th></th>
          {theadData.map((item) => (
            <th className={`fontsize_14`} key={item}>
              {item}
            </th>
          ))}
        </tr>
      </thead>
      <tbody className={`${Styles.tbody}`}>
        {titleColumnData.map((item, firstIndex) => (
          <tr key={item}>
            <td className={`fontsize_14`}>{item}</td>
            {[...new Array(theadData.length).keys()].map((_, i) => (
              <td key={_}>
                {readOnly ? (
                  <p>
                    {typeof extraTd === "function"
                      ? extraTd(extraData?.[firstIndex]?.[i + 1], firstIndex, i)
                      : extraTd}
                  </p>
                ) : (
                  <input
                    type="text"
                    disabled={readOnly}
                    placeholder="请输入"
                    data-first-index={firstIndex}
                    data-last-index={i + 1}
                    onChange={handleChange}
                    value={value?.[firstIndex][i + 1] ?? ""}
                  />
                )}
              </td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
};

export default Index;
